// 人设服务
import { BaseService } from '../../shared/services/base-service'
import type { ApiResponse } from '../../../types/api'

// 人设相关类型定义
export interface CharacterProfile {
  id?: number
  bookId?: number
  characterProfile: string // JSON字符串，包含多个人物设定
  remark?: string // 备注，用于标识该套角色设定对应的小说时期
  version?: number // 版本号
  isActive?: number // 角色启用状态标识，1表示启用，0表示未启用
  createTime?: string
  updateTime?: string
}

// 人设服务类
export class CharacterProfileService extends BaseService {
  private static instance: CharacterProfileService

  private constructor() {
    super()
  }

  public static getInstance(): CharacterProfileService {
    if (!CharacterProfileService.instance) {
      CharacterProfileService.instance = new CharacterProfileService()
    }
    return CharacterProfileService.instance
  }
  /**
   * 获取指定书籍的人设版本列表
   */
  async getCharacterProfilesByBookId(bookId: number): Promise<CharacterProfile[]> {
    try {
      // 使用GET请求获取人设版本列表
      const response = await this.get(`/book-roles/versions?bookId=${bookId}`)
      
      // 检查响应数据是否为数组
      if (response.data && Array.isArray(response.data)) {
        return response.data
      }
      
      // 如果响应数据是单个对象，将其包装在数组中
      if (response.data && typeof response.data === 'object') {
        return [response.data]
      }
      
      // 如果响应数据不是数组或对象，返回空数组
      console.warn('获取人设数据格式不正确，期望数组或对象，实际:', typeof response.data, response.data)
      return []
    } catch (error) {
      console.error('获取人设版本列表失败:', error)
      return []
    }
  }

  // 获取指定版本的书籍人设
  async getCharacterProfileByBookIdAndVersion(bookId: number, version: number): Promise<CharacterProfile | null> {
    const response = await this.get<CharacterProfile>(`/book-roles/version?bookId=${bookId}&version=${version}`)
    return response.data || null
  }



  // 添加新人设版本
  async addCharacterProfile(data: Partial<CharacterProfile>): Promise<ApiResponse<CharacterProfile>> {
    return await this.post<CharacterProfile>(`/book-roles`, data)
  }

  // 更新人设版本
  async updateCharacterProfile(data: Partial<CharacterProfile>): Promise<ApiResponse<CharacterProfile>> {
    // 确保isActive为数字类型
    const submitData = {
      ...data,
      isActive: Number(data.isActive) || 0
    }
    
    // 调试日志：检查updateCharacterProfile方法的参数
    console.log('character-profile-service - updateCharacterProfile参数:', {
      originalData: data,
      submitData: submitData,
      id: submitData.id,
      bookId: submitData.bookId,
      version: submitData.version,
      remark: submitData.remark,
      isActive: submitData.isActive,
      isActiveType: typeof submitData.isActive
    })
    
    return await this.put<CharacterProfile>(`/book-roles/version`, submitData)
  }

  // 删除人设版本
  async deleteCharacterProfile(bookId: number, version: number): Promise<ApiResponse<any>> {
    return await this.delete<any>(`/book-roles?bookId=${bookId}&version=${version}`)
  }

  // 归档人设版本
  async archiveCharacterProfile(data: Partial<CharacterProfile>): Promise<ApiResponse<any>> {
    return await this.post<any>(`/book-roles/archive`, data)
  }

  // 获取人设历史版本
  async getCharacterProfileVersions(bookId: number): Promise<CharacterProfile[]> {
    const response = await this.get<CharacterProfile[]>(`/book-roles/versions?bookId=${bookId}`)
    return response.data || []
  }

  // 获取派系统计
  async getFactionStatistics(bookId: number): Promise<Record<string, number>> {
    const response = await this.get<Record<string, number>>(`/book-roles/faction-stats?bookId=${bookId}`)
    return response.data || {}
  }

  // 获取最新人设
  async getLatestCharacterProfile(bookId: number): Promise<CharacterProfile | null> {
    const response = await this.get<CharacterProfile>(`/book-roles/latest?bookId=${bookId}`)
    return response.data || null
  }

  // 获取当前启用状态的角色
  async getActiveCharacterProfile(bookId: number): Promise<CharacterProfile | null> {
    const response = await this.get<CharacterProfile>(`/book-roles/active?bookId=${bookId}`)
    return response.data || null
  }

  // 批量保存人设
  async batchSaveCharacterProfiles(profiles: CharacterProfile[]): Promise<CharacterProfile[]> {
    const response = await this.post<CharacterProfile[]>(`/book-roles/batch-generate-stream`, profiles)
    return response.data || []
  }

  // 流式生成人设
  async generateCharactersStream(requestData: any): Promise<any> {
    // 构建请求体，符合StreamGenerationRequest格式
    const requestBody = {
      modelId: requestData.modelId,
      systemPromptId: requestData.systemPromptId,
      userPrompt: requestData.userPrompt,
      bookId: requestData.bookId,
      business: requestData.business || '人设生成',
      abortSignal: requestData.abortSignal
    };
    
    // 构建请求头
    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
      'Accept': 'text/plain;charset=UTF-8'
    }
    
    // 添加Authorization头
    const token = await import('../../shared/services/api-config').then(m => m.ApiConfig.getToken());
    if (token) {
      headers['Authorization'] = `Bearer ${token}`;
    }
    
    // 使用fetch API调用通用流式接口
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'http://127.0.0.1:8080'}/book-roles/batch-generate-stream`, {
      method: 'POST',
      headers: headers,
      body: JSON.stringify(requestBody)
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    return response;
  }
}

// 创建单例实例
export const characterProfileService = CharacterProfileService.getInstance()